package com.lzx.reggie.controller

import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.lzx.reggie.common.R
import com.lzx.reggie.entity.Category
import com.lzx.reggie.service.CategoryService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*


@RestController
@RequestMapping("/category")

class CategoryController {

    companion object {
        val log: Logger = LoggerFactory.getLogger(AddressBookController::class.java)
    }

    @Autowired
    private lateinit var categoryService: CategoryService

    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping
    fun save(@RequestBody category: Category): R<Any> {
        log.info("category:{}", category)
        categoryService.save(category)
        return R.success("新增分类成功")
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    fun page(page: Int, pageSize: Int): R<Page<Category>> {
        //分页构造器
        val pageInfo = Page<Category>(page.toLong(), pageSize.toLong())
        //分页查询
        categoryService.page(pageInfo,
            // 条件构造器
            KtQueryWrapper(Category::class.java).apply {
                // 添加排序条件，根据sort进行排序
                orderByAsc(Category::sort)
            })
        return R.success(pageInfo)
    }

    /**
     * 根据id删除分类
     * @param id
     * @return
     */
    @DeleteMapping
    fun delete(id: Long): R<String> {
        log.info("删除分类，id为：{}", id)

        //categoryService.removeById(id);
        categoryService.remove(id)
        return R.success("分类信息删除成功")
    }

    /**
     * 根据id修改分类信息
     * @param category
     * @return
     */
    @PutMapping
    fun update(@RequestBody category: Category): R<String> {
        log.info("修改分类信息：{}", category)
        categoryService.updateById(category)
        return R.success("修改分类信息成功")
    }

    /**
     * 根据条件查询分类数据
     * @param category
     * @return
     */
    @GetMapping("/list")
    fun list(category: Category): R<List<Category>> {
        return R.success(
            categoryService.list(
                //条件构造器
                KtQueryWrapper(Category::class.java).apply {
                    //添加条件
                    eq(category.type != null, Category::type, category.type)
                    //添加排序条件
                    orderByAsc(Category::sort)
                    orderByDesc(Category::updateTime)
                })
        )
    }
}
